package com.whjk.system.biz.controller;

import com.whjk.core.common.annotation.Inner;
import com.whjk.core.common.api.Result;
import com.whjk.core.security.component.JwtUtil;
import com.whjk.core.security.component.UserAuthentication;
import com.whjk.system.biz.service.impl.MyUserDetailsService;
import com.whjk.system.data.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
@Api(tags = "后台管理端登录")
public class SysLoginController {
    @Resource
    MyUserDetailsService myUserDetailsService;

    @Inner
    @ApiOperation("登录")
    @PostMapping("login")
    public Result<Map<String, Object>> login(@Validated(SysUser.review.class) @RequestBody SysUser sysUser) {
        UserAuthentication userDetails = (UserAuthentication) myUserDetailsService.loadUserByUsername(sysUser.getAccount());
        Assert.isTrue(new BCryptPasswordEncoder().matches(sysUser.getPassword(), userDetails.getPassword()), "密码错误!");
        String token = JwtUtil.generateToken(userDetails.getExtendUserBean(), userDetails.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("menu", userDetails.getMenu());
        return Result.ok(map);
    }
}
